<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getSerch">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="intro" label="部门介绍" width="120" sortable>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门主管" width="120" sortable>
      </el-table-column>

      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>


      <el-table-column prop="state" label="状态" width="120" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">正常</span>
          <span v-else style="color: purple">禁用</span>
        </template>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.search.currentPage"
          :page-sizes="[5,10,15,20]"
          :page-size="this.search.pageSize"
          style="float: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>

		<!--编辑和新增界面-->
		<el-dialog title="编辑" :visible.sync="savetFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门介绍" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门经理" prop="manager">
          <!--下拉选项
  :key=""  //唯一标识
  :label 选择之后展示到选择框中的值
  :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
     必须要写  value-key="id"
-->
          <el-select v-model="saveForm.manager" clearable value-key="id" placeholder="请选择">

            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>




			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="savetFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->

	</section>
</template>

<script>
// <!--引入mock技术 不需要，要使用后台传值的数据-->
// 	import util from '../../common/js/util'
// 	//import NProgress from 'nprogress'
// 	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
        search: {
					keyword: '',
          pageSize:10,
          currentPage:1
				},
        // pageInfo:{
        //   list: [],
        //   total: 0
        // },
        pageInfo:{
          list: [],
          total: 0,
        },

				listLoading: false,
				sels: [],//列表选中列

				savetFormVisible: false,//编辑界面是否显示
				editLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门', trigger: 'blur' }
					]
				},
				//编辑界面数据
				saveForm: {
          id: null,
          name: '',
          path:'',
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          intro:'',
          state:'',

        },
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				addForm: {
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				},

			//	定义部门主管数组
        employees : [],
        //定义父级部门树
        deptTree:[],
      }
		},
		methods: {
		  //获取服部门信息
      getDeptTree(){
        this.$http.get("/department/tree")
        .then(res=>{
          var data = res.data;
          if (data.success){
            this.deptTree=data.data
          }
        })
        .catch(res=>{

        })
      },
		  //获取部门主管信息
      getEmployees(){
        this.$http.get("/employee")
            .then(res=>{
              var data = res.data;
              if(data.success){
                // this.pageInfo = data.data.list
                // this.pageInfo = data.data.total
                this.employees = data.data
              }
            })
            .catch(res=>{})
      },

		  //点击查询
      getSerch(){
        this.search.currentPage=1;
        this.getDepartments()
      },
      handleSizeChange(val) {
        this.search.pageSize = val;
        this.getDepartments()
      },



			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
      //当前页
			handleCurrentChange(val) {
				this.search.currentPage = val;
				this.getDepartments()
			},
			//获取部门列表
      getDepartments() {
			  //发送axios请求，在全局main.js里引入axios
        this.$http.post("/department",this.search)
        .then(res=>{
          console.log(res)
          var data = res.data;
          if(data.success){
            // this.pageInfo = data.data.list
            // this.pageInfo = data.data.total
            this.pageInfo = data.data
          }
        })
        .catch(res=>{})





				// let para = {
				// 	page: this.page,
				// 	name: this.filters.name
				// };
				// this.listLoading = false;//让数据不一直刷新将true改为false
				//NProgress.start();

        //灭有数据不需要一直刷新
				// getUserListPage(para).then((res) => {
				// 	this.total = res.data.total;
				// 	this.users = res.data.users;
				// 	this.listLoading = false;
				// 	//NProgress.done();
				// });
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
              this.$http.delete("/department/"+row.id)
                  .then(res=>{
                    res = res.data;
                    if(res.success){
                      this.$message({ message: '删除成功', type: 'success' });
                      this.search.currentPage = 1
                      this.getDepartments()
                      this.listLoading = false;
                    }
                  }).catch(res=>{
              })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.savetFormVisible = true;
        console.log(row);
        this.saveForm = Object.assign({}, row);

        //不能为null传给定义的对象
        if (!row.manager){
          this.saveForm.manager={id:null,username: ''}
        }
        if (!row.parent){
          this.saveForm.parent={id:null,name: ''}
        }else {
          //父部门不为空，取path

          var split = row.path.split("/");
          var path = [];
          for (let i = 1; i < split.length-1; i++) {
            path.push(Number.parseInt(split[i]))
            this.saveForm.parent = path
          }
        }
        this.getEmployees()
        this.getDeptTree()

			},
			//显示新增界面
			handleAdd: function () {
				this.savetFormVisible = true;
				this.saveForm = {
          id: null,
          name: '',
          path:'',
          manager:{
            id:null,
            username:""
          },
          parent:{
            id:null,
            name:""
          },
          intro:'',
          state:'',
				};
				this.getEmployees()
        this.getDeptTree();

      },
			//编辑
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();

              if (this.saveForm.parent.length>=0){

                  if( this.saveForm.parent.length==0){
                    this.saveForm.parent = {
                      id:null
                    }
                  }else {
                    this.saveForm.parent = {
                      id:this.saveForm.parent[this.saveForm.parent.length-1]
                    }
                  }
              }
              this.$http.put("department",this.saveForm)
              .then(res=>{
                res = res.data
                if (res.success){
                  this.$message({message:"操作成功",type:'success'})
                  this.editLoading = false;
                  this.search.currentPage = 1
                  this.getDepartments()
                  this.savetFormVisible = false;
                }
              })
              .catch()
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							addUser(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getUsers();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
          this.$http.patch("/department",ids)
              .then(res => {
                console.log(res)
                var data = res.data;
                if(data.success){
                  this.$message({ message: '删除成功', type: 'success' });
                  this.listLoading = false
                  this.getDepartments();
                }

              }).catch(res=>{

          })

				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>